package com.baoyouqun.API.sms;

import cn.dev33.satoken.annotation.SaIgnore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/sms")
@SaIgnore
public class SmsController {

    private final SmsService smsService;

    @Autowired
    public SmsController(SmsService smsService) {
        this.smsService = smsService;
    }

    /**
     * 发送短信验证码
     */
    @PostMapping("/send")
    public Map<String, Object> sendCode(@RequestBody Map<String, String> params) {
        Map<String, Object> result = new HashMap<>();

        String phone = params.get("phone");
        String scene = params.get("scene");

        if (phone == null || scene == null) {
            result.put("success", false);
            result.put("msg", "手机号和业务场景不能为空");
            return result;
        }

        String sendResult = smsService.sendVerificationCode(phone, scene);
        if ("success".equals(sendResult)) {
            result.put("success", true);
            result.put("msg", "验证码已发送，请注意查收");
        } else {
            result.put("success", false);
            result.put("msg", sendResult);
        }

        return result;
    }

    /**
     * 验证短信验证码
     */
    @PostMapping("/verify")
    public Map<String, Object> verifyCode(@RequestBody Map<String, String> params) {
        Map<String, Object> result = new HashMap<>();

        String phone = params.get("phone");
        String scene = params.get("scene");
        String code = params.get("code");

        if (phone == null || scene == null || code == null) {
            result.put("success", false);
            result.put("msg", "参数不完整");
            return result;
        }

        boolean verifySuccess = smsService.verifyCode(phone, scene, code);
        if (verifySuccess) {
            result.put("success", true);
            result.put("msg", "验证码验证通过");
        } else {
            result.put("success", false);
            result.put("msg", "验证码错误或已过期");
        }

        return result;
    }
}
